import 'package:dio/dio.dart';
import 'package:word_app/app/modules/model/storage_model.dart';
import 'package:word_app/app/modules/model/user_model.dart';

class AppHttpsClient {
  static String domain = "https://wukongmiliao.com/api/";
  static Dio dio = Dio();
  Httpsclient() {
    dio.options.baseUrl = domain;
    dio.options.connectTimeout = 5000; //5s
    dio.options.receiveTimeout = 5000;
    var usermodelJson = StorageModel.getUserModelData("userAllData");
    if (usermodelJson != null) {
      var usermodel = UserModel.fromJson(usermodelJson);
      if (usermodel.data != null) {
        dio.options.headers = {
          "Content-Type": "application/json",
          "Cookie": "x-token=${usermodel.data!.token}"
        };
      }
    }
  }

  Future get(apiurl, Map<String, dynamic>? data) async {
    try {
      var response;
      if (data == null) {
        response = await dio.get(apiurl);
      } else {
        response = await dio.get(apiurl, queryParameters: data);
      }

      print("请求成功${response}");
      return response;
    } catch (e) {
      print("请求超时");
      return null;
    }
  }

  Future<dynamic> post(apiurl, data) async {
    try {
      var url = "$domain$apiurl";
      var response = await dio.post(url, data: data);
      print("请求成功${response}");
      return response;
    } catch (e) {
      print("请求超时${e}");
      return null;
    }
  }

  Future<Response?> uploadImage(
      List images, String apiurl, Map<String, String> params) async {
    try {
      var url = "$domain$apiurl";

      FormData formData = FormData();
      for (var imageFile in images) {
        formData.files.add(MapEntry(
          'files[]',
          await MultipartFile.fromFile(imageFile.path,
              filename: imageFile.name),
        ));
      }
      params.forEach((key, value) {
        formData.fields.add(MapEntry('key', value));
      });

      Response response = await dio.post(url, data: formData);
      return response;
    } catch (e) {
      return null;
    }
  }
}
